package lt.marsrutai.mobile.android.fragment;

import lt.marsrutai.mobile.android.AppContext;
import lt.marsrutai.mobile.android.R;
import lt.marsrutai.mobile.android.bundle.ScopeDownloadBundleHolder;
import lt.marsrutai.mobile.android.cache.UpdateCacheRequest;
import lt.marsrutai.mobile.android.cache.UpdateCacheRequest.Section;
import lt.marsrutai.mobile.android.exception.DataAccessException;
import lt.marsrutai.mobile.android.model.MobileScope;
import lt.marsrutai.mobile.android.util.PreferenceUtils;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ProgressBar;

import com.actionbarsherlock.app.SherlockFragment;

public class ScopeDownloadFragment extends SherlockFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.scope_download_layout, null);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        setupView();
    }

    private void setupView() {
        CheckBox downloadDataCheckbox = (CheckBox) getActivity().findViewById(R.id.download_data);
        if (null == downloadDataCheckbox) {
            return;
        }

        downloadDataCheckbox
                .setChecked(null != new ScopeDownloadBundleHolder(ScopeDownloadFragment.this.getArguments()).getStoredVersion());
        downloadDataCheckbox.setOnClickListener(new OnClickListener() {

            /**
             * Handle logic here instead of onCheckedChangeListener because when one fragment is swapped with the
             * another onResume is called on checkbox. This in itself checks its saved state and calls OnCheckedChanged
             * listener if there is any. So actions get repeaed after fragments onResume method is called.
             */
            @Override
            public void onClick(View v) {
                ScopeDownloadBundleHolder holder = new ScopeDownloadBundleHolder(ScopeDownloadFragment.this.getArguments());
                CheckBox checkbox = ((CheckBox) v);

                UpdateCacheRequest updateRequest = new UpdateCacheRequest(holder.getScopeFolder(), holder.getScopeName(), Section.SCHEDULES);

                if (checkbox.isChecked()) {
                    AppContext.getCacheUpdateManager().performUpdate(ScopeDownloadFragment.this.getActivity(), updateRequest);

                    // Do not show data download advice when entering schedules activity anymore.
                    PreferenceUtils.setBooleanPreferenceValue(ScopeDownloadFragment.this.getActivity(),
                            PreferenceUtils.SCHEDULE_ACTIVITY_OPENED, Boolean.TRUE);

                }
                else {
                    try {
                        MobileScope mobileScope = AppContext.getDataService().getScopeInfo(holder.getScopeFolder());
                        if (null != mobileScope.getStoredVersion()) {
                            AppContext.getCacheUpdateManager().showScopeDeleteConfirmationDialog(ScopeDownloadFragment.this.getActivity(),
                                    holder.getScopeFolder(), checkbox);
                        }
                        else {
                            // Notify data download service that we do not want to download this scope anymore.
                            AppContext.getCacheUpdateManager().cancelUpdate(ScopeDownloadFragment.this.getActivity(), updateRequest);
                        }
                    }
                    catch (DataAccessException e) {
                        return;
                    }
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();

        ScopeDownloadBundleHolder holder = new ScopeDownloadBundleHolder(ScopeDownloadFragment.this.getArguments());

        // Progress bar is still visible when download is finished while other activity is being active.
        // Hide progress bar whenever resuming this activity.
        ProgressBar progressBar = (ProgressBar) getActivity().findViewById(R.id.download_progress);
        if (null != progressBar) {
            progressBar.setVisibility(View.INVISIBLE);
        }

        CheckBox downloadDataCheckbox = (CheckBox) getActivity().findViewById(R.id.download_data);
        if (null != downloadDataCheckbox) {
            downloadDataCheckbox.setEnabled(true);

            // Get current stored version, which can already by different from the one this fragment got as an
            // argument. Exception is thrown if not data is caches, because network is accessed in the main thread.
            // This is ok, since it means that no data is cached.
            try {
                MobileScope mobileScope = new GetScopeInfoTask().execute(holder.getScopeFolder()).get();
                downloadDataCheckbox.setChecked(null != mobileScope && null != mobileScope.getStoredVersion());
            }
            catch (Exception ex) {
                downloadDataCheckbox.setChecked(false);
            }
        }
    }

    /**
     * Wrapper class to get mobile scope in non-main thread.
     *
     * @author Martynas
     */
    private class GetScopeInfoTask {

        private String scopeFolder;

        public GetScopeInfoTask execute(String scopeFolder) {
            this.scopeFolder = scopeFolder;
            return this;
        }

        protected MobileScope get() {
            try {
                return AppContext.getDataService().getScopeInfo(scopeFolder);
            }
            catch (DataAccessException e) {
                return null;
            }
        }
    }
}
